'''
Author: xubing
Date: 2024-01-17 12:43:47
LastEditors: xubing
LastEditTime: 2024-01-23 10:32:41
Description: file content
'''
import os
import time
from datetime import datetime
from functools import wraps

import requests
from loguru import logger
from sqlalchemy import create_engine
import json

# 获取项目路径
current_path = os.path.dirname(__file__)

logger.add('logs/app_log_{time}.log', rotation='00:00')
# 获取当前时间
current_time = datetime.now()
current_date = current_time.strftime("%Y-%m-%d")
# 格式化时间为 YYYY-MM-DD HH:MM:SS 形式

formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(" =====================================")
print(" | Current Date:", current_date, "         |")
print(" | Current Time:", formatted_time, "|")
print(" =====================================")
print("\n")


def pretty_time(seconds):
    if seconds < 60:
        return "%d second" % seconds
    if seconds < 60 * 60:
        return "%d minute %d seconds" % (int(seconds / 60), seconds % 60)
    if seconds < 60 * 60 * 60:
        return "%d hour %d minute %d seconds" % (
            int(seconds / 3600),
            int(seconds % 60),
            seconds % 60,
        )


# 计算时间函数
def timeit(func):
    def wrapper(*args, **kw):
        start_time = time.time()
        result = func(*args, **kw)
        cost_time = time.time() - start_time
        print("==" * 25)
        print(
            "Current Function [%s] run time is %s"
            % (func.__name__, pretty_time(cost_time))
        )
        print("==" * 25)
        return result

    return wrapper


def time_decorator_with_prompt(prompt_infor):
    def time_decorator(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            start_time = time.time()
            result = f(*args, **kwargs)
            print("==")
            print(prompt_infor + ", Cost Time =", time.time() - start_time)
            return result

        return decorated

    return time_decorator


@timeit
# @time_decorator_with_prompt("hello")
def test_time():
    time.sleep(2)


def send_msg_to_feishu(msg):
    url = "https://open.feishu.cn/open-apis/bot/v2/hook/be702221-2cae-4195-b0ad-f76ef4540d37"
    headers = {'Content-Type': 'application/json'}
    data = {"msg_type": "text", "content": {"text": str(msg)}}
    response = requests.post(url, headers=headers, data=json.dumps(data))
    print(response.status_code)
    print("飞书信息发送成功!")
    

# 写入mysql数据库 以日期为分区
def write_to_mysql(table_name,if_exists,df):
    try:
        engine = create_engine(
                    "mysql+pymysql://root:12345678@192.168.0.110:3306/lianjia")
        # 将DataFrame对象写入到 mysql 表中, 需要指定表名、数据库连接对象、是否覆盖或追加、是否写入索引等参数
        df.to_sql(name=table_name,
                con=engine,
                if_exists=if_exists,
                index=False)  # replace
        msg = "写入MySQL成功!"
        logger.info(msg)
    except:
        msg = "写入MySQL失败,请检查!!"
        logger.error(msg)
    send_msg_to_feishu(msg)
    